#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Datetime: 2021/3/10 下午4:53
# @Author  : HUANG Xiong
# @Site    : 
# @File    : pinyin_tool.py
# @Software: PyCharm 

"""
脚本说明：汉字转拼音的工具
"""
from pypinyin import lazy_pinyin, load_phrases_dict
from pypinyin.contrib.mmseg import seg, retrain


class PinyinModel:

    def get_pinyin_initial(self, words, condition=None, out_type=2):
        """
        得到每个汉字的拼音首字母

        :param words: 中文字符串
        :param condition: 可以在列表中添加多个符号处理条件，数据类型：字典。
                          type：0-直接删除符号，1-删除符号及符号内部内容(符合条件的全部)
                          symbol：待处理的符号，目前支持："()", "（）", "-", "/", "+", "."
                          示例：condition = [{"type": 0, "symbol":"()"}, {"type": 0, "symbol":"+"}]
        :param out_type: 输出类型，默认是2：输出简称小写
                         1-全称：每个词语全部小写，示例：nihao
                         2-简称：每个词语拼音首字母小写，示例：nh
        :return:
        """
        find_all = lambda data, s: [r for r in range(len(data)) if data[r] == s]
        # 是否对原字符串进行处理
        if condition:
            for item in condition:
                if item["type"] == 0:
                    if "/" in item["symbol"] or "-" in item["symbol"] or "+" in item["symbol"] or "." in item["symbol"]:
                        words = words.replace(item["symbol"], "")
                    elif "()" in item["symbol"]:
                        words = words.replace("(", "")
                        words = words.replace(")", "")

                    elif "（）" in item["symbol"]:
                        words = words.replace("（", "")
                        words = words.replace("）", "")

                elif item["type"] == 1:
                    # 暂时解决分级基金标志，即"/"前后标识
                    if "/" in item["symbol"]:
                        index = find_all(words, item["symbol"])
                        if len(index) > 1:
                            for secondIndex in range(len(index)):
                                secondIndexItem = find_all(words, item["symbol"])
                                words = words[:secondIndexItem[0] - 1] + words[secondIndexItem[0] + 2:]
                        else:
                            words = words[:index[0] - 1] + words[index[0] + 2:]
                    elif "-" in item["symbol"]:
                        pass
                    elif "(" in item["symbol"]:
                        indexLeft = find_all(words, "(")
                        indexRight = find_all(words, ")")
                        if len(indexLeft) > 1:
                            for secondIndex in range(len(indexLeft)):
                                secondIndexLeft = find_all(words, "(")
                                secondIndexRight = find_all(words, ")")
                                words = words[:secondIndexLeft[0]] + words[secondIndexRight[0] + 1:]
                        else:
                            words = words[:indexLeft[0]] + words[indexRight[0] + 1:]
                    elif "（" in item:
                        indexLeft = find_all(words, "（")
                        indexRight = find_all(words, "）")

                        if len(indexLeft) > 1:
                            for secondIndex in range(len(indexLeft)):
                                secondIndexLeft = find_all(words, "（")
                                secondIndexRight = find_all(words, "）")
                                words = words[:secondIndexLeft[0]] + words[secondIndexRight[0] + 1:]
                        else:
                            words = words[:indexLeft[0]] + words[indexRight[0] + 1:]

        # 汉字转拼音
        retrain(seg)
        load_phrases_dict(self.initial_dict())
        wordsPinyin = lazy_pinyin(seg.cut(words))

        specialInfo = ["QDII", "QDIIA", "QDIIB", "QDIIC", "QDIID", "QDIIE",
                       "FOF", "FOFA", "FOFB", "FOFC", "FOFD", "FOFE",
                       "LOF", "LOFA", "LOFB", "LOFC", "LOFD", "LOFE",
                       "QDIIFOF", "QDIIFOFA", "QDIIFOFB", "QDIIFOFC", "QDIIFOFD", "QDIIFOFE",
                       "QDIILOF", "QDIILOFA", "QDIILOFB", "QDIILOFC", "QDIILOFD", "QDIILOFE",
                       "QDIILOFFOF", "QDIILOFFOFA", "QDIILOFFOFB", "QDIILOFFOFC", "QDIILOFFOFD", "QDIILOFFOFE",
                       "QDIIFOFLOF", "QDIIFOFLOFA", "QDIIFOFLOFB", "QDIIFOFLOFC", "QDIIFOFLOFD", "QDIIFOFLOFE",
                       "ETF", "ETFA", "ETFB", "ETFC", "ETDF", "ETFE",
                       "MSCI", "REIT", "CES",
                       'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH',
                       'BC', 'BD', 'BE', 'BF', 'BG', 'BH',
                       'CD', 'CE', 'CF', 'CG', 'CH',
                       'DE', 'DF', 'DG', 'DH',
                       ]

        if out_type == 1:
            try:
                if wordsPinyin:
                    pinyinTemp = list(map(self.normal_lower, wordsPinyin))
                    result_pinyin = ''.join(pinyinTemp)
                    return result_pinyin
            except:
                raise

        elif out_type == 2:
            # 生成首字母
            try:
                if wordsPinyin:
                    words_pinyin_list = []
                    for index in range(len(wordsPinyin)):
                        if any(wordsPinyin[index] == wordTemp for wordTemp in specialInfo) or \
                                wordsPinyin[index].isdigit():
                            words_pinyin_list.append(str(wordsPinyin[index]).strip())
                        else:
                            words_pinyin_list.append(str(wordsPinyin[index][0]).strip())
                    result_pinyin = ''.join(words_pinyin_list)
                    return result_pinyin
            except:
                raise

    def initial_dict(self):
        userDict = {
            '长信': [['chang'], ['xin']], '长盛': [["chang"], ["sheng"]], '长盈': [['chang'], ['ying']],
            '朝阳': [['chao'], ['yang']],
            '广发': [['guang'], ['fa']],
            '行业': [['hang'], ['ye']],

            '供给': [['gong'], ['ji']],
            '晟纯': [['sheng'], ['chun']],
            'QDII': [['QDII']],
            'FOF': [['FOF']],
            'LOF': [['LOF']],
            'QDIIFOF': [['QDIIFOF']],
            'QDIILOF': [['QDIILOF']],
            'QDIILOFFOF': [['QDIILOFFOF']],
            'QDIIFOFLOF': [['QDIIFOFLOF']],
            'ETF': [['ETF']],
            'TMT': [['TMT']],
            'REIT': [['REIT']],
            'MSCI': [['MSCI']],
            'AH': [['AH']],
            'CES': [['CES']],
        }
        return userDict

    def normal_capitalize(self, name):
        """
        :param name: str = "www.runoob.com"
                     print(str.upper())          # 把所有字符中的小写字母转换成大写字母
                     print(str.lower())          # 把所有字符中的大写字母转换成小写字母
                     print(str.capitalize())     # 把第一个字母转化为大写字母，其余小写
                     print(str.title())          # 把每个单词的第一个字母转化为大写，其余小写
        :return:
        """

        return name.capitalize()

    def normal_upper(self, name):
        return name.upper()

    def normal_lower(self, name):
        return name.lower()

    def normal_title(self, name):
        return name.title()


if __name__ == '__main__':
    resultPinyin = PinyinModel()
    '''
    # 1.多音字问题
    print(resultPinyin.getPinyinInitial("长信银利精选混合"))
    print(resultPinyin.getPinyinInitial("国泰金龙混合行业混合"))
    '''
    # 2.特殊字符问题
    print(resultPinyin.get_pinyin_initial("你好"))
    print(resultPinyin.get_pinyin_initial("你好", out_type=1))
    print(resultPinyin.get_pinyin_initial("中银全球策略(QDII-FOF)",
                                          condition=[{"type": 0, "symbol": "()"}, {"type": 0, "symbol": "-"}]))
